/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.serializer;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.dailydev.wave.robot.RobotException;
import org.json.JSONException;
import org.json.JSONObject;

import com.metaparadigm.jsonrpc.JSONSerializer;
import com.metaparadigm.jsonrpc.MarshallException;
import com.metaparadigm.jsonrpc.SerializerState;
import com.metaparadigm.jsonrpc.UnmarshallException;

/**
 * Generic implementation of {@link ISerializer} interface. The implementation
 * internally uses singleton instance of {@link JSONSerializer} with default
 * serializer registration.
 * 
 * @author Roman Bosak, DailyDev.org
 */
public class Serializer<K> implements ISerializer<K> {

    /**
     * {@link Serializer}'s logger
     */
    private static Logger log = Logger.getLogger(Serializer.class.getName());

    private static final JSONSerializer jsonSerializer;

    static {
        jsonSerializer = new JSONSerializer();
        try {
            jsonSerializer.registerDefaultSerializers();
        } catch (Exception e) {
            log.log(Level.SEVERE, "Unable to initialize serializer", e);
        }
    }

    /**
     * 
     */
    public Serializer() {
        super();
    }

    /** {@inheritDoc} */
    @Override
    public K deserialize(String toDeserialize) throws RobotException {
        try {
            JSONObject jsonObject = new JSONObject(toDeserialize);
            return (K) jsonSerializer.unmarshall(new SerializerState(), Object.class, jsonObject);
        } catch (JSONException jsonx) {
            throw new RobotException("Unable to parse wavelet context document to JSON object", jsonx);
        } catch (UnmarshallException e) {
            throw new RobotException("Unable to parse wavelet context document to JSON object", e);
        }
    }

    /** {@inheritDoc} */
    @Override
    public String serialize(K toSerialize) throws RobotException {
        try {
            return jsonSerializer.toJSON(toSerialize);
        } catch (MarshallException e) {
            throw new RobotException("Unable to marshal JSON object into JSON String", e);
        }
    }

}
